package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.jsonwebtoken.Jwt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 登录界面
     * @param userLoginDTO  微信的临时唯一标识
     * @return 微信的唯一标识
     */
    @Override
    public UserLoginVO getByUserDTOOpenId(UserLoginDTO userLoginDTO) {
        // 根据传输的数据 去微信 解析 openid
        // 因为解析 需要写的代码太长 所以直接调用方法 简洁业务层代码
        UserLoginVO userLoginVO = new UserLoginVO();
        String openid = getByUserDTOOpenid(userLoginDTO.getCode());
        //log.info("微信ID：{}",openid);
        //解析后 判断 是否解析到openid  没有直接抛异常
        if (openid == null) throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        //有的话判断数据库是否存储了 此唯一标识  没有就存储一份 有就无需存储

        User user =  userMapper.selectIsOpenId(openid);
        if (user == null){  //去数据库存储openid
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insertUser(user);
        }
        //生成token令牌
        Map<String,Object> list = new HashMap<>();
        list.put(JwtClaimsConstant.USER_ID,user.getId());
        //调用工具类加密                   // 密钥                           // 时间                    自定义信息
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), list);
        //封装对象给前端
        userLoginVO.setToken(jwt);
        userLoginVO.setId(user.getId());
        userLoginVO.setOpenid(openid);
        return userLoginVO;
    }

    private String getByUserDTOOpenid(String code) {
        //调用 工具类 去微信解析code
        Map paramMap = new HashMap();
        paramMap.put("appid","wxed21f9a11ab96e70");
        paramMap.put("secret","fd21f8861ee82f48fd878df4667d4531");
        paramMap.put("js_code",code);
        paramMap.put("grant_type","authorization_code");
        String doGet = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        //只需要获取ID返回 无需其他信息
        JSONObject jsonObject = JSON.parseObject(doGet);
        String openid = jsonObject.getString("openid");
        return openid;

    }

}
